<template>
  <div :id="id" class="w-full">
    <!-- -->
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { MdEditor, schema, parseContent, markdownSerializer } from "./index";

defineOptions({
  name: "MdEditor"
});

const props = defineProps({
  content: {
    type: String,
    default: ""
  },
  id: {
    type: String,
    default: "editor"
  }
});

const mdEditor = ref<MdEditor>(null);

defineExpose({
  get editor() {
    return mdEditor.value;
  },
  getContent() {
    if (!mdEditor.value?.editor?._view?.state?.doc) {
      console.warn("MD编辑器 - 编辑器未初始化或文档不存在");
      return "";
    }

    try {
      // 将 ProseMirror 文档转换为 Markdown 格式，使用类型安全的方式
      const doc = mdEditor.value.editor._view.state.doc;
      // 使用类型断言确保兼容性
      const markdown = markdownSerializer.serialize(doc as any);
      console.log("MD编辑器 - 获取Markdown内容:", markdown);
      return markdown;
    } catch (error) {
      console.error("MD编辑器 - 获取Markdown内容失败:", error);
      // 如果转换失败，返回纯文本作为备用
      try {
        return mdEditor.value.editor._view.state.doc.toString();
      } catch (fallbackError) {
        console.error("MD编辑器 - 获取纯文本内容也失败:", fallbackError);
        return "";
      }
    }
  },
  getPlainText() {
    // 提供获取纯文本的方法
    if (!mdEditor.value?.editor?._view?.state?.doc) {
      return "";
    }
    return mdEditor.value.editor._view.state.doc.toString();
  },
  setContent(content: string) {
    // 设置编辑器内容
    if (!mdEditor.value?.editor?._view) {
      console.warn("MD编辑器 - 编辑器未初始化，无法设置内容");
      return;
    }

    try {
      // 使用我们自定义的解析函数，确保schema兼容性
      const doc = parseContent(content);
      const transaction = mdEditor.value.editor._view.state.tr.replaceWith(
        0,
        mdEditor.value.editor._view.state.doc.content.size,
        doc.content
      );
      mdEditor.value.editor._view.dispatch(transaction);
      console.log("MD编辑器 - 设置内容成功:", content);
    } catch (error) {
      console.error("MD编辑器 - 设置内容失败:", error);

      // 如果设置内容失败，尝试重新创建编辑器
      try {
        console.log("尝试重新创建编辑器...");
        mdEditor.value = new MdEditor(`#${props.id}`, content);
      } catch (recreateError) {
        console.error("重新创建编辑器也失败:", recreateError);
      }
    }
  },

  // 添加一个获取编辑器状态的方法，便于调试
  getEditorState() {
    if (!mdEditor.value?.editor) {
      return null;
    }
    return {
      hasEditor: !!mdEditor.value.editor,
      hasView: !!mdEditor.value.editor._view,
      hasState: !!mdEditor.value.editor._view?.state,
      hasDoc: !!mdEditor.value.editor._view?.state?.doc,
      docContent: mdEditor.value.editor._view?.state?.doc?.textContent || "",
      docSize: mdEditor.value.editor._view?.state?.doc?.content?.size || 0
    };
  }
});

onMounted(() => {
  mdEditor.value = new MdEditor(`#${props.id}`, props.content);
});
</script>

<style lang="scss" scoped>
.w-full {
  display: flex;
  flex-direction: column;
  height: 100%;
}

:deep(.ProseMirror-menubar-wrapper) {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 300px;

  .menubar {
    flex-shrink: 0;
    margin-bottom: 0;
    padding: 8px 12px;
    background: #f8f9fa;
    border: 1px solid #dcdfe6;
    border-bottom: none;
    border-radius: 6px 6px 0 0;

    .menuicon {
      display: inline-block;
      padding: 6px 10px;
      margin: 0 4px 0 0;
      border-radius: 4px;
      cursor: pointer;
      font-size: 13px;
      font-weight: 500;
      color: #606266;
      background: transparent;
      transition: all 0.2s ease;
      border: 1px solid transparent;

      &:hover {
        background: #e6f7ff;
        color: #409eff;
        border-color: #b3d8ff;
      }

      &:active {
        background: #d1ecf1;
        transform: scale(0.95);
      }

      &:last-child {
        margin-right: 0;
      }
    }
  }

  .ProseMirror {
    flex: 1;
    min-height: 200px;
    max-height: none;
    padding: 16px;
    border: 1px solid #dcdfe6;
    border-top: none;
    border-radius: 0 0 6px 6px;
    font-size: 14px;
    line-height: 1.6;
    font-family:
      -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue",
      Arial, sans-serif;
    background: #fff;
    overflow-y: auto;
    resize: none;
    outline: none;

    &:focus {
      border-color: #409eff;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
    }

    // Markdown 内容样式
    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
      margin: 1em 0 0.5em 0;
      font-weight: 600;
      line-height: 1.4;
      color: #2c3e50;
    }

    h1 {
      font-size: 1.8em;
      border-bottom: 2px solid #eee;
      padding-bottom: 0.3em;
    }

    h2 {
      font-size: 1.5em;
      border-bottom: 1px solid #eee;
      padding-bottom: 0.3em;
    }

    h3 {
      font-size: 1.25em;
    }

    p {
      margin: 0.5em 0;
      color: #34495e;
    }

    strong {
      font-weight: 600;
      color: #2c3e50;
    }

    em {
      font-style: italic;
      color: #7f8c8d;
    }

    blockquote {
      margin: 1em 0;
      padding: 0.5em 1em;
      border-left: 4px solid #409eff;
      background: #f8f9fa;
      color: #5a6c7d;

      p {
        margin: 0.25em 0;
      }
    }

    ul,
    ol {
      margin: 0.5em 0;
      padding-left: 2em;

      li {
        margin: 0.25em 0;
        color: #34495e;
      }
    }

    code {
      padding: 0.2em 0.4em;
      background: #f1f3f4;
      border-radius: 3px;
      font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
      font-size: 0.9em;
      color: #e83e8c;
    }

    pre {
      margin: 1em 0;
      padding: 1em;
      background: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 6px;
      overflow-x: auto;

      code {
        background: none;
        padding: 0;
        color: #333;
      }
    }

    // 表格样式
    table {
      width: 100%;
      border-collapse: collapse;
      margin: 1em 0;
      background: #fff;
      border: 1px solid #dcdfe6;
      border-radius: 6px;
      overflow: hidden;
      font-size: 14px;

      th,
      td {
        padding: 8px 12px;
        text-align: left;
        border: 1px solid #e4e7ed;
        vertical-align: top;

        p {
          margin: 0;
        }
      }

      th {
        background: #f5f7fa;
        font-weight: 600;
        color: #303133;
        border-bottom: 2px solid #dcdfe6;
      }

      td {
        background: #fff;
        color: #606266;

        &:hover {
          background: #f5f7fa;
        }
      }

      tr {
        &:nth-child(even) td {
          background: #fafafa;
        }

        &:hover td {
          background: #f0f9ff;
        }
      }
    }

    // ProseMirror 表格特定样式
    .ProseMirror-widget {
      // 列调整器样式
      .column-resize-handle {
        background: #409eff;
        width: 4px;
        cursor: col-resize;
        position: absolute;
        right: -2px;
        top: 0;
        bottom: 0;
      }
    }

    // 表格选中状态
    .selectedCell {
      background: #ecf5ff !important;
      border: 2px solid #409eff !important;
    }
  }
}

// 当编辑器处于焦点时的整体样式
:deep(.ProseMirror-focused) {
  .menubar {
    border-color: #409eff;
    box-shadow: 0 -2px 0 0 rgba(64, 158, 255, 0.2);
  }
}
</style>
